<template>
  <main class="max-w-5xl mx-auto py-8 px-4">
    <h2 class="text-xl font-bold mb-4">图片收藏夹</h2>
    <!-- 批量操作栏 -->
    <div v-if="favoriteImages.length" class="flex items-center gap-2 mb-2">
      <input
        type="checkbox"
        :checked="isAllSelected"
        @change="isAllSelected ? clearSelect() : selectAll()"
      />
      <span>已选 {{ selectedIds.length }}/{{ favoriteImages.length }}</span>
      <Button size="sm" variant="ghost" @click="selectAll">全选</Button>
      <Button size="sm" variant="ghost" @click="clearSelect">清空</Button>
      <Button
        size="sm"
        variant="outline"
        :disabled="!selectedIds.length"
        @click="batchUnfavorite"
        >批量取消收藏</Button
      >
      <Button
        size="sm"
        variant="outline"
        :disabled="!selectedIds.length"
        @click="batchExport"
        >批量导出链接</Button
      >
    </div>
    <!-- 收藏图片列表 -->
    <div class="grid grid-cols-2 md:grid-cols-3 gap-4">
      <div
        v-for="(img, index) in favoriteImages"
        :key="img.id"
        class="relative group"
      >
        <input
          type="checkbox"
          class="absolute left-2 top-2 z-10"
          :checked="selectedIds.includes(String(index))"
          @change="toggleSelect(String(index))"
        />
        <!-- 复用MaterialListView的卡片结构或ImageCard组件 -->
        <div class="relative group-hover:scale-105 transition-all duration-300">
          <img
            :src="img"
            :alt="img"
            class="w-full h-50 object-cover rounded-lg"
          />
          <!-- 右上角取消收藏按钮 -->
          <button
            class="absolute right-2 top-2 z-20 bg-white/80 rounded-full p-1 shadow hover:scale-110 transition"
            @click.stop="unfavorite(img.id)"
            title="取消收藏"
          >
            <svg
              viewBox="0 0 24 24"
              fill="currentColor"
              class="w-6 h-6 text-pink-500"
            >
              <path
                d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41 0.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"
              />
            </svg>
          </button>
        </div>
        <!-- <div class="mt-2 text-sm text-center truncate">{{ img }}</div> -->
      </div>
    </div>
    <div v-if="!favoriteImages.length" class="text-gray-400 text-center py-12">
      暂无收藏图片
    </div>
  </main>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { batchGetImageUrls } from "@/api/search";
import { Button } from "@/components/ui/button";

const favoriteImages = ref<any[]>([]);
const selectedIds = ref<string[]>([]);

function getFavoriteIds() {
  return JSON.parse(localStorage.getItem("favoriteImageIds") || "[]");
}

async function loadFavorites() {
  let ids = getFavoriteIds();
  if (ids.length) {
    const res = await batchGetImageUrls(ids);
    favoriteImages.value = res || [];
  } else {
    favoriteImages.value = [];
  }
  clearSelect();
}

onMounted(loadFavorites);

function unfavorite(id: string) {
  let ids = getFavoriteIds();
  ids = ids.filter((i: string) => i !== id);
  localStorage.setItem("favoriteImageIds", JSON.stringify(ids));
  loadFavorites();
}

function batchUnfavorite() {
  let ids = getFavoriteIds();
  ids = ids.filter((id: string) => !selectedIds.value.includes(id));
  localStorage.setItem("favoriteImageIds", JSON.stringify(ids));
  loadFavorites();
}

function batchExport() {
  const urls = favoriteImages.value
    .filter(img => selectedIds.value.includes(img.id))
    .map(img => img.url)
    .join("\n");

  // 优先使用现代 Clipboard API
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard
      .writeText(urls)
      .then(() => {
        console.log("链接已复制到剪贴板");
      })
      .catch(err => {
        console.warn("Clipboard API 失败，使用降级方案:", err);
        fallbackCopyToClipboard(urls);
      });
  } else {
    // 降级方案：使用传统的 document.execCommand
    fallbackCopyToClipboard(urls);
  }
}

// 降级复制方案
function fallbackCopyToClipboard(text: string) {
  try {
    // 创建临时文本区域
    const textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.position = "fixed";
    textArea.style.left = "-999999px";
    textArea.style.top = "-999999px";
    document.body.appendChild(textArea);

    // 选择文本并复制
    textArea.focus();
    textArea.select();
    const successful = document.execCommand("copy");

    // 清理临时元素
    document.body.removeChild(textArea);

    if (successful) {
      console.log("链接已复制到剪贴板");
    } else {
      console.error("复制失败");
    }
  } catch (err) {
    console.error("复制失败:", err);
  }
}

function toggleSelect(id: string) {
  if (selectedIds.value.includes(id)) {
    selectedIds.value = selectedIds.value.filter(i => i !== id);
  } else {
    selectedIds.value.push(id);
  }
}
function selectAll() {
  selectedIds.value = favoriteImages.value.map(img => img.id);
}
function clearSelect() {
  selectedIds.value = [];
}
const isAllSelected = computed(
  () =>
    selectedIds.value.length === favoriteImages.value.length &&
    favoriteImages.value.length > 0
);
</script>
